package com.xpsoft.oa.service.produce.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.ContextUtil;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.produce.MaterialPurchaseDao;
import com.xpsoft.oa.dao.produce.MaterialPurchaseInfoDao;
import com.xpsoft.oa.model.produce.MaterialPurchase;
import com.xpsoft.oa.model.produce.MaterialPurchaseInfo;
import com.xpsoft.oa.service.produce.MaterialPurchaseService;

public class MaterialPurchaseServiceImpl extends BaseServiceImpl<MaterialPurchase> implements MaterialPurchaseService{
	private MaterialPurchaseDao dao;
	@Autowired
	private MaterialPurchaseInfoDao materialPurchaseInfoDao;
	public MaterialPurchaseServiceImpl(MaterialPurchaseDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveMaterialPurchase(MaterialPurchase materialPurchase,
			String dataList) {
		// TODO Auto-generated method stub
		dao.save(materialPurchase);
		Boolean isNew = true;//新增标志
		if(materialPurchase.getId()!=null){
			isNew = false;
		}
		dao.save(materialPurchase);
		if(StringUtils.isNotBlank(dataList)){
			List<MaterialPurchaseInfo> materialPurchaseInfoList = JsonUtil.fromJsonTypesWithDate(dataList,
					new TypeToken<List<MaterialPurchaseInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(MaterialPurchaseInfo materialPurchaseInfo:materialPurchaseInfoList){
					if(materialPurchaseInfo.getId()!=null){//修改的记录
						idList.add(materialPurchaseInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					materialPurchaseInfoDao.deleteMaterialPurchaseInfos(materialPurchase.getId(), idList);
				}
			}
			for(MaterialPurchaseInfo materialPurchaseInfo:materialPurchaseInfoList){
				materialPurchaseInfo.setPurchasePlan(materialPurchase);
				materialPurchaseInfo.setCreateUser(ContextUtil.getCurrentUser());
				materialPurchaseInfo.setCreateTime(new Date());
				materialPurchaseInfoDao.save(materialPurchaseInfo);
			}
		}
	}

}